package main

import (
	"fmt"
	"time"
	"math/rand"
)

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(
				time.Duration(
					rand.Intn(1500)) * time.Millisecond)

			out <- i
			i++
		}
	}()
	return out
}
func worker(id int,c chan int)  {
	for n := range c{
		time.Sleep(time.Second)
		fmt.Printf("worker %d ,receive  %d \n", id, n)

	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id,c)
	return c
}


func main() {
	var c1, c2 = generator(), generator()
	//var  worker  chan int // w = nil
	w := createWorker(0)
	n := 0
	var values [] int
	//hasVaule := false
	tm := time.After(10 * time.Second)

	tick := time.Tick(time.Second)
	for {
		var avtiveWorker  chan <- int
		var avtiveValue int
		if len(values)>0 {
			avtiveWorker = w
			avtiveValue = values[0]
		}
		select {
		case n = <-c1:
			//fmt.Println("Received from c1:", n)
			//hasVaule = true
			values = append(values, n)
		case n = <-c2:
			//fmt.Println("Received from c2:", n)
			//hasVaule = true
			values = append(values, n)
		case avtiveWorker <- avtiveValue:
			values = values[1:]
			//hasVaule = false
			//default:
		//	fmt.Println("No Received ")
		//
		case <- time.After(800 * time.Millisecond):
			fmt.Println("Time out")
		case <-tick:
			fmt.Println("Queue Len = ",len(values))
		case <-tm:
			fmt.Println("Bye ")
			return
		}

	}
}
